package base.jfinal.plugin;

import java.io.*;
import java.net.URL;
import java.util.*;

import base.jfinal.JsonUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.log4j.Logger;
import base.util.PropertiesContent;

import com.jfinal.kit.StrKit;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
/**
 * 概要：用于读取sql语句模板的类
 * @author gaby
 *
 */
public class ReadSql {
	static Map<String, String> mapSql;
	static Logger log=Logger.getLogger(ReadSql.class);
	String lineSeparator = System.getProperty("line.separator", "\n");
	/**
	 * 取得sql语句
	 * @param strKey 如：emp.empList  emp为文件名;empList为emp文件里的一个sql语句的Key值
	 * @return
	 */
	public static String getSql(String strKey){
		if(StrKit.isBlank(strKey)) {
            log.error("取得sql语句的关键字为空");
            throw new RuntimeException("取得sql语句的关键字为空");
        }
		if(strKey.indexOf(".")==-1){
            log.error("sql语句的关键字不正确："+strKey);
            throw new RuntimeException("sql语句的关键字不正确："+strKey);
        }
		return mapSql.get(strKey.intern());
	}

	/**
	 * 初始化sql模板
	 */
	public void init(){
		//初始化Map
		mapSql=new HashMap<String, String>();
		BufferedReader br;
		String temp,strSqlKey="";
		LinkedList<String> list = new LinkedList<String>();
		
		try{
			//取得文件名和文件流
			Map<String, FileInputStream> ins = getFile();
			for (Map.Entry<String, FileInputStream> entry:ins.entrySet()){
				br=new BufferedReader(new InputStreamReader(entry.getValue(),"UTF-8"));
				list.clear();
				 while ((temp = br.readLine()) != null) {
					 if(StrKit.isBlank(temp)) continue;//如果取得空，则继续循环
					 //如果---，则取得sql
					 if(temp.trim().startsWith("---")){
						 strSqlKey=entry.getKey()+"."+list.pollFirst();
					 }else if(temp.trim().startsWith("===")){
						 mapSql.put(strSqlKey, getSqlToStr(list));
						 list.clear();
					 }else{
						 list.addLast(temp);
					 }
				 }
				 if(list.size()>0){
					 mapSql.put(strSqlKey, getSqlToStr(list));
				 }
			}
		}catch(Exception ex){
			log.error("初始化sql失败："+ex.getMessage());
		}
	}
	
	public String getSqlToStr(LinkedList<String> ls){
		StringBuffer strReturn=new StringBuffer();
		for (String string : ls) {
			strReturn.append(string).append(lineSeparator);
		}
		return strReturn.toString();
	}

	private Map<String, FileInputStream> getFile() {
		Map<String,FileInputStream> mp=new HashMap<String, FileInputStream>();
		String prefix;
		URL URL=ClassSearcher.class.getResource(PropertiesContent.get("sql.root")+"/");
		File file=new File(URL.getFile());
		for(File f: file.listFiles()){
			prefix=f.getName().substring(f.getName().indexOf(".")+1);
			if(prefix.toLowerCase().intern()=="md".intern()||prefix.toLowerCase().intern()=="sql".intern()){
				try {
					mp.put(f.getName().replace("."+prefix, ""), new FileInputStream(f));
				} catch (FileNotFoundException e) {
				}
			}
		}
		return mp;
	}
}
